#!/bin/sh

EXAMPLE_TEST_LOCATION=@EXAMPLE_TEST_LOCATION@

simulation_module="module/kedr_sample_indicator_test_module.ko"
point_name="common"

indicator_module="${EXAMPLE_TEST_LOCATION}/kedr_sample_indicator.ko"
indicator_name="periodic"

debugfs="@KEDR_TEST_DIR@/debugfs"

point_dir="${debugfs}/kedr_fault_simulation/points/${point_name}"

simulate()
{
	echo 123 > "${debugfs}/kedr_indicator_internal_test_module/simulate"
}

do_commands_script="sh @TEST_SCRIPTS_DIR@/do_commands.sh"
commands_file="./commands.txt"

cat > "$commands_file" << eof

on_load @KEDR_FAULT_SIMULATION_LOAD_COMMAND@ || ! printf "Cannot load fault simulation module into kernel.\n"
on_unload @RMMOD@ "@KEDR_FAULT_SIMULATION_NAME@" || ! printf "Cannot unload fault simulation module.\n"
on_load @INSMOD@ "${simulation_module}" || ! printf "Cannot load module with simulation point into kernel.\n"
on_unload @RMMOD@ "${simulation_module}" || ! printf "Cannot unload module with simulation point.\n"
on_load @INSMOD@ "${indicator_module}" || ! printf "Cannot load indicator module into kernel.\n"
on_unload @RMMOD@ "${indicator_module}" || ! printf "Cannot unload indicator module.\n"

on_load mkdir -p "${debugfs}"
on_load mount -t debugfs debugfs "${debugfs}"
on_unload umount "${debugfs}"

eof

if ! ./build_example.sh $EXAMPLE_TEST_LOCATION; then
    exit 1
fi

if ! $do_commands_script "$commands_file" load; then
	printf "Cannot initialize test.\n"
	exit 1
fi

echo "${indicator_name} 3" > ${point_dir}/current_indicator

if test $? -ne 0; then
	printf "Cannot set indicator for the point.\n"
	$do_commands_script "$commands_file" unload
	exit 1
fi

if ! test -e "${point_dir}/period"; then
	printf "File 'period' is not created by the indicator.\n"
	$do_commands_script "$commands_file" unload
	exit 1
fi

if ! test -r "${point_dir}/period"; then
	printf "File 'period' created by the indicator cannot be read.\n"
	$do_commands_script "$commands_file" unload
	exit 1
fi

if test "`cat "${point_dir}/period"`" != "3"; then
	printf "It was expected that file 'period' would contatin '%s', but '%s' has been read from it.\n" "3" "`cat "${point_dir}/period"`"
	$do_commands_script "$commands_file" unload
	exit 1
fi

if ! simulate ; then
	printf "The first call to the function should not fail with \"every third\" scenario.\n"
	$do_commands_script "$commands_file" unload
	exit 1
fi

if ! simulate ; then
	printf "The second call to the function should not fail with \"every third\" scenario.\n"
	$do_commands_script "$commands_file" unload
	exit 1
fi

if simulate ; then
	printf "The third call to the function should fail with \"every third\" scenario.\n"
	$do_commands_script "$commands_file" unload
	exit 1
fi


if ! $do_commands_script "$commands_file" unload; then
	printf "Errors occured while finalizing the test.\n"
	exit 1
fi
